import { BoolType, IModuleWithState } from '../types'
import { setDomBoolVal, setDomDataItemVal } from '../utils'
import { bus1 } from './bus'

interface IOutputState {
    out_en: BoolType
    value: number
}

interface IOutput extends IModuleWithState<IOutputState> {}

/**
 * output模块
 */
export const output: IOutput = {
    name: 'output',
    state: {
        out_en: 0,
        value: 0,
    },
    async setState(prop, value) {
        this.state[prop] = value
        if (prop === 'out_en') {
            setDomBoolVal(prop, this.state[prop] as BoolType)
        } else if (prop === 'value') {
            setDomDataItemVal('.output .data-item-val', this.state[prop])
        }
        if (prop !== 'value') {
            this.change!()
        }
        return
    },
    async change() {
        // 当out_en为1时，输出数据
        if (this.state.out_en === 1) {
            const value = bus1.getData()
            this.setState('value', value)
        }
    },
    init() {
        // 设置out_en的初始值
        setDomBoolVal('out_en', this.state.out_en)
        // 设置output
        setDomDataItemVal('.output .data-item-val', this.state['value'])
    },
}
